//
//  DatasourceView.swift
//  maozzi-rss
//
//  Created by 帽子 on 2020/7/19.
//  Copyright © 2020 帽子. All rights reserved.
//  数据源view

import SwiftUI

struct DatasourceView: View {
    @EnvironmentObject var userData: UserData

    var body: some View {
        List {
            Section(header: Text("数据源设置").font(.caption)) {
                ForEach(UserData.datasources, id: \.id) { datasourceItem in
                    Button(action: {
                        var arr = self.userData.userDatasources
                        let item = datasourceItem.encode()
                        if arr.contains(item) {
                            arr.remove(at: arr.firstIndex(of: item)!)
                        } else {
                            arr.append(item)
                        }
                        self.userData.userDatasources = arr
                        UserDefaults.standard.set(arr, forKey: "userDatasources")
                    }) {
                        HStack {
                            Text(datasourceItem.name)
                            Spacer()
                            if self.userData.userDatasources.contains(datasourceItem.encode()) {
                                Image(systemName: "checkmark")
                                    .imageScale(.small)
                                    .foregroundColor(.blue)
                            }
                        }
                    }
                }
            }
        }
    }
}

struct DatasourceView_Previews: PreviewProvider {
    static var previews: some View {
        DatasourceView().environmentObject(UserData())
    }
}
